package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.shopping.converter.ContentConverter;
import com.cskaoyan.shopping.dal.entitys.Panel;
import com.cskaoyan.shopping.dal.entitys.PanelContentItem;
import com.cskaoyan.shopping.dal.persistence.PanelContentMapper;
import com.cskaoyan.shopping.dal.persistence.PanelMapper;
import com.cskaoyan.shopping.dto.HomePageResponse;
import com.cskaoyan.shopping.dto.PanelContentItemDto;
import com.cskaoyan.shopping.dto.PanelDto;
import com.cskaoyan.shopping.service.IHomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author CR
 * @since 2022/06/17 17:36
 */
@Service
public class IHomeServiceImpl implements IHomeService {

    @Autowired
    PanelMapper panelMapper;
    @Autowired
    PanelContentMapper panelContentMapper;
    @Autowired
    ContentConverter contentConverter;

    /*
         显示首页商品信息，显示的是Panel信息，但是这里注意下，如何获取Panel信息呢？
         1. 先调用 PanelMapper selectPanelContentById，自己看下sql语句，获取 List<Panel>
         2. Panel对象中，少了 List<PanelContentItem> panelContentItems
         3. 因此，需要遍历List中的Panel，在调用PanelContentMapper 的 selectPanelContentAndProductWithPanelId方法
            获取List<PanelContentItem>，利用MapStruct将其转化为 List<PanelContentItemDto>
         4. 然后set 到Panel

     */
    @Override
    public HomePageResponse getHomepage() {
        HomePageResponse homePageResponse = new HomePageResponse();

        try {
            List<Panel> panels = panelMapper.selectPanelContent();
            for (Panel panel : panels) {

                List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
                // List<PanelContentItemDto> panelContentItemDtos = contentConverter.panelContentItem2Dto(panelContentItems);
                panel.setPanelContentItems(panelContentItems);
            }
            List<PanelDto> panelDtos = contentConverter.panels2Dto(panels);

            homePageResponse.setPanelContentItemDtos(panelDtos);
            homePageResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            homePageResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(homePageResponse,e);
        }
        return homePageResponse;
    }
}
